package com.shujushow.common.security;

import com.shujushow.common.session.ShiroSession;
import com.shujushow.common.util.SerializeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Collection;
import java.util.concurrent.TimeUnit;

@Component
public class RedisSessionRepository implements SessionRepository {

    private static final Logger log = LoggerFactory.getLogger(RedisSessionRepository.class);

    private static final String ZCM_SESSION_PREFIX = "zcm-session:";

    @Value("${shiro.globalSessionTimeout:1800}")
    private Long sessionTimeOut;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void saveSession(Session session) {

        if (session == null || session.getId() == null) {
            throw new NullPointerException("session is empty");
        }

        try {
            redisTemplate.opsForValue().set(
                    buildSessionKey(session.getId()),
                    SerializeUtils.serialize(session),
                    sessionTimeOut,
                    TimeUnit.SECONDS
            );
        } catch (Exception exc) {
            log.error("save session[" + session.getId() + "] error", exc);
        }
    }

    @Override
    public void updateSession(Session session) {

        if (session == null || session.getId() == null) {
            throw new NullPointerException("session is empty");
        }

        try {
            redisTemplate.boundValueOps(buildSessionKey(session.getId())).set(
                    SerializeUtils.serialize(session),
                    sessionTimeOut,
                    TimeUnit.SECONDS
            );
        } catch (Exception exc) {
            log.error("update session[" + session.getId() + "] error", exc);
        }
    }

    @Override
    public void refreshSession(Serializable sessionId) {

        if (sessionId == null) {
            throw new NullPointerException("sessionId is empty");
        }

        try {
            redisTemplate.expire(
                    buildSessionKey(sessionId),
                    sessionTimeOut,
                    TimeUnit.SECONDS
            );
        } catch (Exception exc) {
            log.error("refresh session[" + sessionId + "] error", exc);
        }
    }

    @Override
    public void deleteSession(Serializable sessionId) {

        if (sessionId == null) {
            throw new NullPointerException("session id is empty");
        }

        try {
            redisTemplate.delete(buildSessionKey(sessionId));
        } catch (Exception exc) {
            log.error("delete session[" + sessionId + "] error", exc);
        }
    }

    @Override
    public Session getSession(Serializable sessionId) {

        if (sessionId == null) {
            throw new NullPointerException("session id is empty");
        }

        Session session = null;

        try {
            String sessionStr = (String) redisTemplate.boundValueOps(buildSessionKey(sessionId)).get();

            if (StringUtils.isNotEmpty(sessionStr)) {
                session = SerializeUtils.deserialize(sessionStr, ShiroSession.class);
            }

        } catch (Exception exc) {
            log.error("get session[" + sessionId + "] error", exc);
        }

        return session;
    }

    @Override
    public Collection<Session> getAllSessions() {
        return null;
    }

    private String buildSessionKey(Serializable sessionId) {
        return ZCM_SESSION_PREFIX + sessionId;
    }

}
